const indexModel = require('../models/indexModel');

const utils=require('../utils/index')

let myGlobal={}

//果首页
exports.index=function(req,res){
    indexModel.index().then(function(data){
        data[3]=utils.arrFormat(data[3]);
        let result ={
            menus:data[0],
            banners:data[1],
            types:data[2],
            articals:data[3],
            user:req.session.user2
        }

        myGlobal.menus=data[0]
        res.render('index',result)
    })
}

//果登录
exports.loginPage=function(req,res){
    res.render('login')
}

exports.login=function(req,res){
    // res.render(req.body)
    indexModel.login(req.body).then(function(data){
        // console.log(data)
        req.session.user2=data[0];
        res.redirect('/')
    })
}

//果注册
exports.registerPage=function(req,res){
    res.render('register')
}

exports.register=function(req,res){
    indexModel.sendRegister(req.body).then(function(data){
        if(data.affectedRows>0){
            res.redirect('/login')
        }
        
    })
}

exports.detailPage=function(req,res){
   
    indexModel.getOneArtical(req.params.id).then(function(data){
        // console.log(data)
         res.render('detail',{artical:data[0],menus:myGlobal.menus,user:req.session.user2})
    })
}

exports.createArtical=function(req,res){
    if(req.session.user2){
        indexModel.getAllClass().then(function(data){
            res.render('create',{menus:myGlobal.menus,user:req.session.user2,types:data});
        })
        
    }else{
        res.redirect('/login');
    }
}

exports.sendArtical=function(req,res){
    indexModel.sendArtical(req.body).then(function(data){
        if(data.affectedRows>0){
            res.redirect('/')
        }
    })
}